package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constans.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 点赞行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1.参数校验
        if(dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取登录用户id,
        ApUser apUser = AppThreadLocalUtil.getApUser();
        //如果没有登录，则不能执行以下步骤，游客身份
        if(apUser!=null && apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.查看当前用户是否点赞过
        String likekey="USER_LIKE_"+dto.getArticleId();
        Boolean likeFlag = redisTemplate.opsForHash().hasKey(likekey, apUser.getId().toString());
        //3.1 如果点赞过，而此时的动作还是点赞过行为，operation=0，则取消返回
        if(likeFlag && dto.getOperation()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.LIKE_END);
        }

        UpdateArticleMess mess=new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        //3.2 如果点赞过，而此时的动作是取消点赞过行为，operation=1，则删除redis和mongo
        if(likeFlag && dto.getOperation()==1){
            redisTemplate.opsForHash().delete(likekey,apUser.getId().toString());
            mongoTemplate.remove(Query.query(
                    Criteria.where("userId").is(apUser.getId()).and("articleId").is(dto.getArticleId())
            ), ApLikesBehavior.class);

            mess.setAdd(-1);
            //发送消息给kafka
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
            return ResponseResult.okResult("取消点赞成功");
        }
        //3.3 如果没有点赞过，此时的动作是关注点赞过operation=0，则新增redis和mongo
        if(!likeFlag && dto.getOperation()==0){
            redisTemplate.opsForHash().put(likekey,apUser.getId().toString(),"1");
            ApLikesBehavior apLikesBehavior=new ApLikesBehavior();
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setUserId(Long.valueOf(apUser.getId()));
            apLikesBehavior.setArticleId(dto.getArticleId());
            mongoTemplate.save(apLikesBehavior);

            mess.setAdd(1);
            //发送消息给kafka
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
            return ResponseResult.okResult("点赞成功");
        }


        return null;
    }
}
